package com.dai.designpattern.prototype.deep;


import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.List;

/**
 * @author daijiyong
 */
public class Man implements Cloneable, Serializable {

    private int age;
    private String name;
    private List<String> friends;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getFriends() {
        return friends;
    }

    public void setFriends(List<String> friends) {
        this.friends = friends;
    }

    @Override
    public Man clone() {
        try {
            return (Man) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Man deepCloneJson() {
        try {
            String json = JSONObject.toJSONString(this);
            return JSONObject.parseObject(json, Man.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Man deepCloneSerialise() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return (Man) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (oos != null) {
                    oos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String toString() {
        return "Man{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", friends=" + friends +
                '}';
    }
}
